<template>
  <view class="address-form">
    <!-- 表单项 -->
    <view class="form-item">
      <view class="label">收货人</view>
      <input
        class="input"
        :class="{ 'input-error': nameError }"
        type="text"
        placeholder="请填写收货人姓名"
        v-model="addressForm.userName"
        @blur="validateName"
        @input="clearNameError"
      />
      <view v-if="nameError" class="error-text">{{ nameErrorMsg }}</view>
    </view>

    <view class="form-item">
      <view class="label">手机号</view>
      <input
        class="input"
        :class="{ 'input-error': phoneError }"
        type="number"
        maxlength="11"
        placeholder="请输入手机号"
        v-model="addressForm.phone"
        @blur="validatePhone"
        @input="clearPhoneError"
      />
      <view v-if="phoneError" class="error-text">{{ phoneErrorMsg }}</view>
    </view>

    <view class="form-item">
      <view class="label">省市区</view>
      <nut-cell
        :class="{ 'cell-error': regionError }"
        title="选择地址"
        :desc="value.toString() || '请选择地址'"
        @click="visible = true"
      >
      </nut-cell>
      <nut-cascader
        v-model:visible="visible"
        v-model="value"
        text-key="name"
        value-key="name"
        title="选择地址"
        :options="options"
        @change="handleRegionChange"
      ></nut-cascader>
      <view v-if="regionError" class="error-text">{{ regionErrorMsg }}</view>
    </view>

    <view class="form-item">
      <view class="label">详细地址</view>
      <textarea
        class="textarea"
        :class="{ 'textarea-error': addressError }"
        placeholder="请输入详细地址"
        v-model="addressForm.address2"
        @blur="validateAddress"
        @input="clearAddressError"
      />
      <view v-if="addressError" class="error-text">{{ addressErrorMsg }}</view>
      <!-- 地图选择按钮 -->
      <!-- <view class="map-picker" @tap="openMapPicker">
        <text class="icon">📍</text>
        <text class="text">地图选点</text>
      </view> -->
    </view>

    <!-- 默认地址开关 -->
    <view class="default-switch">
      <view class="switch-label">设为默认地址</view>
      <nut-switch v-model="addressForm.isDefault" @change="toggleDefault" />
    </view>

    <!-- 保存按钮 -->
    <view class="btn-wrapper">
      <nut-button class="save-btn" type="primary" @tap="saveAddress"
        >保存</nut-button
      >
    </view>

    <!-- 地图选择器 -->
    <!-- <map
      v-if="showMap"
      class="map-container"
      :latitude="location.latitude"
      :longitude="location.longitude"
      :markers="markers"
      @tap="handleMapTap"
      @markertap="handleMarkerTap"
    >
      <cover-view class="map-toolbar">
        <cover-view class="map-confirm" @tap="confirmLocation">确定</cover-view>
        <cover-view class="map-cancel" @tap="cancelMap">取消</cover-view>
      </cover-view>
    </map> -->

    <!-- 地图加载遮罩 -->
    <view v-if="showMap" class="map-overlay"></view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import Taro from "@tarojs/taro";
import http from "@/utils/http";
import area from "./data.json";

Taro.setNavigationBarTitle({
  title: "添加地址",
});

const visible = ref(false);
const value = ref(["广西壮族自治区", "南宁市", "青秀区"]);

const options = ref(area);

// 校验相关
const phoneError = ref(false);
const phoneErrorMsg = ref("");
const nameError = ref(false);
const nameErrorMsg = ref("");
const regionError = ref(false);
const regionErrorMsg = ref("");
const addressError = ref(false);
const addressErrorMsg = ref("");

// 地址表单数据
const addressForm = ref({
  userName: "",
  phone: "",
  // region: "",
  province: "",
  city: "",
  district: "",
  address2: "",
  isDefault: false,
});

// 地图相关状态
const showMap = ref(false);
const location = reactive({
  latitude: 30.27415,
  longitude: 120.15515,
});
const markers = ref([]);
const selectedLocation = ref(null);

// 处理省市区选择变化
function handleRegionChange(value: any) {
  console.log("省市区", value);
  // addressForm.value.region = value.join("/");
  // 这里可以解析出省市区分别存储
  if (value.length >= 1) addressForm.value.province = value[0];
  if (value.length >= 2) addressForm.value.city = value[1];
  if (value.length >= 3) addressForm.value.district = value[2];
  
  // 清除省市区错误提示
  clearRegionError();
}

// 切换默认地址
function toggleDefault(e) {
  console.log("切换默认地址", e);
  addressForm.value.isDefault = e;
}

// 校验手机号
function validatePhone() {
  const phone = addressForm.value.phone;
  if (!phone) {
    phoneError.value = true;
    phoneErrorMsg.value = "请输入手机号";
    return false;
  }
  
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(phone)) {
    phoneError.value = true;
    phoneErrorMsg.value = "请输入正确的手机号格式";
    return false;
  }
  
  phoneError.value = false;
  phoneErrorMsg.value = "";
  return true;
}

// 清除手机号错误提示
function clearPhoneError() {
  if (phoneError.value) {
    phoneError.value = false;
    phoneErrorMsg.value = "";
  }
}

// 校验收货人姓名
function validateName() {
  const name = addressForm.value.userName.trim();
  if (!name) {
    nameError.value = true;
    nameErrorMsg.value = "请填写收货人姓名";
    return false;
  }
  
  if (name.length < 2) {
    nameError.value = true;
    nameErrorMsg.value = "收货人姓名至少2个字符";
    return false;
  }
  
  nameError.value = false;
  nameErrorMsg.value = "";
  return true;
}

// 清除姓名错误提示
function clearNameError() {
  if (nameError.value) {
    nameError.value = false;
    nameErrorMsg.value = "";
  }
}

// 校验省市区
function validateRegion() {
  if (!value.value || value.value.length < 3) {
    regionError.value = true;
    regionErrorMsg.value = "请选择省市区";
    return false;
  }
  
  regionError.value = false;
  regionErrorMsg.value = "";
  return true;
}

// 清除省市区错误提示
function clearRegionError() {
  if (regionError.value) {
    regionError.value = false;
    regionErrorMsg.value = "";
  }
}

// 校验详细地址
function validateAddress() {
  const address = addressForm.value.address2.trim();
  if (!address) {
    addressError.value = true;
    addressErrorMsg.value = "请填写详细地址";
    return false;
  }
  
  if (address.length < 5) {
    addressError.value = true;
    addressErrorMsg.value = "详细地址至少5个字符";
    return false;
  }
  
  addressError.value = false;
  addressErrorMsg.value = "";
  return true;
}

// 清除详细地址错误提示
function clearAddressError() {
  if (addressError.value) {
    addressError.value = false;
    addressErrorMsg.value = "";
  }
}

const params = Taro.getCurrentInstance().router?.params;
onMounted(() => {
  if (params?.id) {
    http
      .postQuery(`/api/user/getAddressById`, {
        id: params?.id || "",
      })
      .then((res) => {
        console.log("res", res);
        if (res.code == 0) {
          const obj = res.data.columns;
          addressForm.value.userName = obj.userName;
          addressForm.value.phone = obj.phone;
          addressForm.value.address2 = obj.address2;
          addressForm.value.isDefault = obj.status == 1;
          const address = obj.address1.split(",");
          console.log("address", address);
          addressForm.value.province = address[0];
          addressForm.value.city = address[1];
          addressForm.value.district = address[2];
          value.value = address;
        }
      });
  }
});

// 打开地图选择器
function openMapPicker() {
  //   Taro.chooseAddress({
  //     success: (res) => {
  //       console.log("地址", res);
  //       addressForm.value.name = res.userName;
  //       addressForm.value.phone = res.telNumber;
  //     },
  //   });
  //   return;
  // 获取当前位置（需要用户授权）
  Taro.getLocation({
    type: "gcj02",
    success: (res) => {
      console.log("地址", res);
      location.latitude = res.latitude;
      location.longitude = res.longitude;
      showMap.value = true;
      //   updateMarker();
    },
    fail: () => {
      // 如果获取位置失败，使用默认位置
      showMap.value = true;
      //   updateMarker();
    },
  });
}

// 更新地图标记
// function updateMarker() {
//   markers.value = [
//     {
//       id: 0,
//       latitude: location.latitude,
//       longitude: location.longitude,
//       title: "选择的位置",
//       iconPath: "/static/marker.png", // 需要准备标记图标
//       width: 30,
//       height: 30,
//     },
//   ];
// }

// 处理地图点击事件
async function handleMapTap(e) {
  location.latitude = e.detail.latitude;
  location.longitude = e.detail.longitude;
  console.log("点击位置", e.detail);

  const res = await Taro.request({
    url: "https://apis.map.qq.com/ws/geocoder/v1/",
    data: {
      location: `${e.detail.longitude},${e.detail.latitude}`,
      key: "QYTBZ-YCWCZ-ATRXS-7MWIA-SBJD6-EBF4A",
      get_poi: 0,
    },
  });
  console.log("解析地址", res);

  //   http.get(`https://apis.map.qq.com/ws/geocoder/v1/`, {
  //     location: `${e.detail.longitude},${e.detail.latitude}`,
  //     radius: 1000,
  //     key: `5UQBZ-3CUKW-WRURZ-3I4LN-7N6WK-ZGF75`,
  //     extensions: "base",
  //     get_poi: 1,
  //   }).then((res) => {
  //     console.log("地址", res);
  //   });

  //   updateMarker();

  // 调用逆地理编码获取地址名称
  //   Taro.request({
  //     url: "https://restapi.amap.com/v3/geocode/regeo",
  //     data: {
  //       key: "您的高德地图API密钥", // 请替换为实际API密钥
  //       location: `${e.detail.longitude},${e.detail.latitude}`,
  //       radius: 1000,
  //       extensions: "base",
  //     },
  //     success: (res) => {
  //       if (res.data.status === "1") {
  //         const address = res.data.regeocode.formatted_address;
  //         selectedLocation.value = {
  //           address,
  //           latitude: e.detail.latitude,
  //           longitude: e.detail.longitude,
  //         };
  //       }
  //     },
  //   });
}

// 确认选择的位置
function confirmLocation() {
  if (selectedLocation.value) {
    addressForm.value.detail = selectedLocation.value.address;
  }
  showMap.value = false;
}

// 取消地图选择
function cancelMap() {
  showMap.value = false;
}

// 保存地址
function saveAddress() {
  // 表单验证
  const isNameValid = validateName();
  const isPhoneValid = validatePhone();
  const isRegionValid = validateRegion();
  const isAddressValid = validateAddress();
  
  // 如果有任何校验失败，则停止提交
  if (!isNameValid || !isPhoneValid || !isRegionValid || !isAddressValid) {
    return;
  }

  // 提交表单
  console.log("保存地址", addressForm.value);
  // 这里可以调用API保存地址
  http
    .postQuery(`/api/user/updateAddress`, {
      id: params?.id || "",
      userName: addressForm.value.userName,
      phone: addressForm.value.phone,
      address1: [
        addressForm.value.province,
        addressForm.value.city,
        addressForm.value.district,
      ].join(","),
      address2: addressForm.value.address2,
      status: addressForm.value.isDefault ? 1 : 0,
    })
    .then((res) => {
      console.log("res", res);
      if (res.code == 0) {
        Taro.showToast({
          title: "保存成功",
          icon: "success",
        });
        const pages = Taro.getCurrentPages();
        const currentPage = pages[pages.length - 1];
        const eventChannel = currentPage.getOpenerEventChannel();
        eventChannel.emit("updates", {
          data: "test",
        });

        Taro.navigateBack({
          delta: 1,
        });
      } else {
        Taro.showToast({
          title: res.data,
          icon: "error",
        });
      }
    });
}
</script>

<style lang="scss">
.address-form {
  padding: 30rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
  box-sizing: border-box;

  .form-item {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;

    .label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 20rpx;
      font-weight: 500;
    }

    .input {
      width: 100%;
      height: 80rpx;
      font-size: 28rpx;
      color: #333;
      border-bottom: 1px solid #f5f5f5;
      
      &.input-error {
        border-bottom-color: #ff4757;
      }
    }
    
    .error-text {
      color: #ff4757;
      font-size: 24rpx;
      margin-top: 10rpx;
    }

    .textarea {
      width: 100%;
      height: 160rpx;
      font-size: 28rpx;
      color: #333;
      line-height: 1.5;
      margin-bottom: 20rpx;
      border: 1px solid #eee;
      padding: 10rpx;
      border-radius: 8rpx;
      
      &.textarea-error {
        border-color: #ff4757;
      }
    }

    // 地图选择按钮样式
    .map-picker {
      display: flex;
      align-items: center;
      padding: 15rpx 20rpx;
      background-color: #f9f9f9;
      border-radius: 8rpx;
      border: 1px solid #eee;

      .icon {
        margin-right: 10rpx;
      }

      .text {
        font-size: 26rpx;
        color: #666;
      }
    }
  }

  .default-switch {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 60rpx;

    .switch-label {
      font-size: 28rpx;
      color: #333;
    }
  }

  .btn-wrapper {
    padding: 0 30rpx;

    .save-btn {
      width: 100%;
      // height: 90rpx;
      // line-height: 90rpx;
      // text-align: center;
      // background: linear-gradient(to right, #ff9844, #ff6034);
      // color: #fff;
      // font-size: 32rpx;
      // border-radius: 45rpx;
      // border: none;
    }
  }

  // 地图容器样式
  .map-container {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1001;
    height: 100vh;
    width: 100vw;
  }

  // 地图工具栏
  .map-toolbar {
    position: absolute;
    bottom: 40rpx;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    justify-content: space-between;
    width: 80%;

    .map-confirm,
    .map-cancel {
      width: 300rpx;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      background: #ff6034;
      color: white;
      border-radius: 40rpx;
      font-size: 32rpx;
    }

    .map-cancel {
      background: #999;
    }
  }

  // 地图遮罩层
  .map-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 1000;
  }
}
.nut-cell {
  padding-inline: 20rpx !important;
}
.nut-cell__value{
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 2;
}

.cell-error .nut-cell__title,
.cell-error .nut-cell__value {
  color: #ff4757 !important;
}
</style>
